import {
  GetUserConfig,
  SetUserConfig,
  MergeUniqueSort,
  HumanTime,
  SetThemeMode,
  GetVersion,
  IsDebugMode
} from "./common.js";

let config, debug = false;

$(document).ready(function(){
  /**
   * @since 2024-09-19 主函数
   */
  Main();
});

/**
 * @title 主函数
 * @author start2004
 * @since 2024-09-19
 *
 * @return {null}
 */
async function Main(){
  /**
   * @since 2024-09-19 获取配置信息
   */
  config = await GetUserConfig();
  // console.log(config);
  SetThemeMode(config);

  /**
   * @since 2024-10-30 渲染文字，标题，按钮
   */
  let idArray = new Array("back", "options", "add", "minute", "notification", "sound", "new_tab_text", "bar_text", "sound_desc", "theme_mode", "theme_mode_auto", "theme_mode_light", "theme_mode_dark");
  for(const id of idArray){
    // console.log(id, chrome.i18n.getMessage(id));
    $("#"+ id).html(chrome.i18n.getMessage(id));
  }

  /**
   * @since 2024-09-19 渲染时间选项
   * @since 2024-09-30 渲染音频选项
   * @since 2025-02-27 渲染外观主题模式
   */
  RenderTimeList();
  RenderAudio();
  RenderThemeMode();

  /**
   * @since 2024-09-30 增加按钮监听
   */
  AddListen();

  /**
   * @since 2025-08-26 版本号
   */
  let version = await GetVersion();
  $("#version").html(version);

  /**
   * @since 2025-08-26 开发者版本，添加测试版本信息
   */
  let debug = await IsDebugMode();
  if(debug){
    $("#version").on("click", function (){
      window.open("../pages/option.html");
    });
  } else {}
}

/**
 * @title 渲染时间选项
 * @author start2004
 * @since 2024-09-19
 *
 * @return {null}
 */
function RenderTimeList(){
  /**
   * @since 2024-09-19 渲染时间选项
   */
  let defaultList = [60, 300, 600, 1800, 2700, 3600];
  let timeList = MergeUniqueSort(defaultList, config["custom-time"]);

  /**
   * @since 2024-09-19 渲染html
   */
  let htmlArray = new Array(), html, checked;
  for(const time of timeList){
    /**
     * @since 2024-09-20 判断是否选中
     */
    if(config["checked-time"].includes(time)){
      checked = "checked"
    } else {
      checked = "";
    }

    /**
     * @since 2024-09-20 是否自定义
     * @since 2024-09-20 拼接checkbox-html
     * @since 2024-09-20 转换人类可读时间
     */
    if(defaultList.includes(time)){
      html = '<div class="time-item">\n' +
        '    <input type="checkbox" name="time-option" value="'+ time +'" '+ checked +'>\n' +
        '    <span class="time-custom">'+ HumanTime(time) +'</span>\n' +
        '  </div>';
    } else {
      html = '<div class="time-item">\n' +
        '    <input type="checkbox" name="time-option" value="'+ time +'" '+ checked +'>\n' +
        '    <span class="time-custom-text">'+ HumanTime(time) +'</span>\n' +
        '    <button class="delete-btn" data-time="'+ time +'">X</button>\n' +
        '  </div>';
    }
    htmlArray.push(html);
  }
  $("#time-list").html(htmlArray.join(""));

  /**
   * @since 2024-09-20 增加删除按钮的监听
   */
  $(".delete-btn").click(function() {
    DeleteCustomTime($(this).data("time"));
  });

  /**
   * @since 2024-09-20 时间选项checkbox的监听
   */
  $('input[name="time-option"]').change(function() {
    UpdateCheckedTime();
  });
}

/**
 * @title 渲染音频选项
 * @author start2004
 * @since 2024-09-30
 *
 * @return {null}
 */
function RenderAudio(){
  /**
   * @since 2024-09-30 渲染选中音频
   */
  let audioArray = new Array(), checked, audioText;
  for(let i=0; i<8; i++){
    if(i == config["audio"]){
      checked = "checked";
    } else {
      checked = "";
    }
    if(i == 0){
      audioText = chrome.i18n.getMessage("none");
    } else {
      audioText = chrome.i18n.getMessage("sound_") + i;
    }
    audioArray.push('<div class="audio-item"><input type="radio" name="audio" value="'+ i +'" '+ checked +'><span data-audio="'+ i +'">'+ audioText +'</span></div>');
  }
  $("#audio-list").html(audioArray.join(""));

  /**
   * @since 2024-09-30 音频radio监听
   */
  $('input[name="audio"]').on('click', function() {
    let i = $(this).val();
    UpdateAudio(i);

    /**
     * @since 2024-10-31 播放音频
     */
    PlayAudio(i);
  });

  /**
   * @since 2024-09-30 试听音频
   */
  $('.audio-item span').on('click', function() {
    let i = $(this).data('audio');

    /**
     * @since 2024-10-31 播放音频
     */
    PlayAudio(i);
  });
}

/**
 * @title 渲染外观主题选项
 * @author start2004
 * @since 2025-02-27
 *
 * @return {null}
 */
function RenderThemeMode(){
  /**
   * @since 2025-02-27 选中外观主题
   */
  let themeMode = config["theme-mode"];
  $("#"+ themeMode).prop("checked", true);

  /**
   * @since 2025-02-27 监听选项
   */
  $('input[name="theme-mode"]').on('click', function() {
    let val = $(this).val();
    UpdateThemeMode(val);
  });

  /**
   * @since 2025-02-27 监听文本
   */
  $('#theme_mode_light').on('click', function() {
    $("#light").prop("checked", true);
    UpdateThemeMode("light");
  });
  $('#theme_mode_dark').on('click', function() {
    $("#dark").prop("checked", true);
    UpdateThemeMode("dark");
  });
}

/**
 * @title 增加监听
 * @author start2004
 * @since 2024-09-30
 *
 * @return {null}
 */
function AddListen(){
  /**
   * @since 2024-09-20 自定义时间，添加按钮的监听
   */
  $("#add").click(function() {
    AddCustomTime();
  });

  /**
   * @since 2024-09-30 通知方式，选中
   */
  for(let k in config["notification"]){
    $("#"+ config["notification"][k]).prop("checked", true);
  }

  /**
   * @since 2024-09-30 增加监听
   */
  $('input[name="notification"]').change(function() {
    UpdateNotification();
  });
}

/**
 * @title 添加自定义时间选项
 * @author start2004
 * @since 2024-09-20
 *
 * @return {null}
 */
async function AddCustomTime(){
  /**
   * @since 2024-09-20 获取自定义时间
   */
  let customTime = $("#add-time").val();
  customTime = parseInt(customTime*60);

  /**
   * @since 2024-09-20 是否有效时间
   */
  if (customTime > 0) {
    /**
     * @since 2024-09-20 添加自定义时间，并去重
     */
    config["checked-time"] = MergeUniqueSort(config["checked-time"], [customTime]);
    config["custom-time"] = MergeUniqueSort(config["custom-time"], [customTime]);

    /**
     * @since 2024-09-20 保存配置
     */
    SetUserConfig(config);

    /**
     * @since 2024-09-20 渲染时间选项
     */
    RenderTimeList();
  } else {}

  /**
   * @since 2024-09-20 清空input
   */
  $("#add-time").val("");
}

/**
 * @title 删除自定义时间选项
 * @author start2004
 * @since 2024-09-20
 *
 * @param {int} time 时间,单位秒
 * @return {null}
 */
async function DeleteCustomTime(time){
  /**
  * @since 2024-09-20 删除自定义时间
  */
  config["checked-time"] = config["checked-time"].filter(item => item !== time);
  config["custom-time"] = config["custom-time"].filter(item => item !== time);

  /**
  * @since 2024-09-20 保存配置
  */
  await SetUserConfig(config);

  /**
  * @since 2024-09-20 渲染时间选项
  */
  RenderTimeList();
}

/**
 * @title 更新选中的时间
 * @author start2004
 * @since 2024-09-20
 *
 * @return {null}
 */
async function UpdateCheckedTime(){
  /**
   * @since 2024-09-20 checked选中的时间集合
   */
  let checkedTime = new Array();
  $('input[name="time-option"]:checked').each(function() {
    checkedTime.push(parseInt($(this).val()));
  });
  config["checked-time"] = checkedTime;

  /**
   * @since 2024-09-20 保存配置
   */
  await SetUserConfig(config);
}

/**
 * @title 更新通知方式
 * @author start2004
 * @since 2024-09-30
 *
 * @return {null}
 */
async function UpdateNotification() {
  /**
   * @since 2024-09-30 通知方式
   */
  let notification = new Array();
  $('input[name="notification"]:checked').each(function () {
    notification.push($(this).attr("id"));
  });
  config["notification"] = notification;

  /**
   * @since 2024-09-30 保存配置
   */
  await SetUserConfig(config);
}

/**
 * @title 更新音频
 * @author start2004
 * @since 2024-09-30
 *
 * @param {int} i 音频序号
 * @return {null}
 */
async function UpdateAudio(i){
  if(config["audio"] == i) return;

  /**
   * @since 2024-09-30 更新音频，并保存
   */
  config["audio"] = i;
  await SetUserConfig(config);
}

/**
 * @title 播放音频
 * @author start2004
 * @since 2024-10-31
 *
 * @param {int} i 音频序号
 * @return {null}
 */
function PlayAudio(i){
  if(i > 0){
    $("#audio").attr("src", "../assets/audio/"+ i +".mp3");
    document.getElementById('audio').play();
  } else {}
}

/**
 * @title 更新外观主题
 * @author start2004
 * @since 2025-02-27
 *
 * @param {string} val 外观主题
 * @return {null}
 */
async function UpdateThemeMode(val) {
  if(config["theme-mode"] == val) return;

  /**
   * @since 20245-02-27 更新主题，并保存
   */
  config["theme-mode"] = val;
  await SetUserConfig(config);

  /**
   * @since 2025-02-27 重新加载主题
   */
  SetThemeMode(config);
}